// 指数数据Vue组件
const ZhishuComponent = {
    template: `
        <div class="zhishu-page">
            <div class="page-header">
                <h2>指数数据</h2>
                <div class="header-actions">
                    <input 
                        type="date" 
                        v-model="selectedQueryDate"
                        style="margin-right: 10px; padding: 8px 12px; border: 1px solid #dcdfe6; border-radius: 4px; font-size: 14px;"
                        @change="handleDateChange">
                    <el-button type="primary" @click="queryByDate" :loading="loading">
                        <i class="el-icon-search"></i>
                        查询
                    </el-button>
                    <el-button @click="loadRecentData" :loading="loading">
                        <i class="el-icon-refresh"></i>
                        最近数据
                    </el-button>
                    <el-button @click="resetSelection">
                        <i class="el-icon-close"></i>
                        清除选择
                    </el-button>
                </div>
            </div>

            <!-- 查询状态提示 -->
            <div class="query-status">
                <el-alert
                    v-if="currentQueryType === 'recent'"
                    title="正在显示最近5条指数数据"
                    type="success"
                    :closable="false"
                    show-icon>
                </el-alert>
                <el-alert
                    v-else-if="currentQueryType === 'date' && selectedQueryDate"
                    :title="'正在显示 ' + selectedQueryDate + ' 的指数数据'"
                    type="info"
                    :closable="false"
                    show-icon>
                </el-alert>
            </div>

            <!-- 指数数据表格 -->
            <div class="zhishu-container">
                <table class="zhishu-table" v-if="zhishuData.length > 0">
                    <thead>
                        <tr>
                            <th>日期</th>
                            <th>指数名</th>
                            <th>开盘价</th>
                            <th>最高价</th>
                            <th>最低价</th>
                            <th>收盘价</th>
                            <th>涨跌额</th>
                            <th>涨跌幅</th>
                            <th>成交量</th>
                            <th>成交额</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr v-for="(item, index) in zhishuData" 
                            :key="item.dateTime"
                            :class="getRowClass(item)"
                            @click="handleRowClick(item)">
                            <td>{{ formatDate(item.dateTime) }}</td>
                            <td>{{ item.zsName || '-' }}</td>
                            <td>{{ formatNumber(item.open) }}</td>
                            <td>{{ formatNumber(item.high) }}</td>
                            <td>{{ formatNumber(item.low) }}</td>
                            <td>
                                <span :style="{ color: getChangeColor(item.zhangdiee), 'font-weight': 'bold' }">
                                    {{ formatNumber(item.close) }}
                                </span>
                            </td>
                            <td>
                                <span :style="{ color: getChangeColor(item.zhangdiee) }">
                                    {{ formatNumber(item.zhangdiee) }}
                                </span>
                            </td>
                            <td>
                                <span :style="{ color: getChangeColor(item.zhangdiefu) }">
                                    {{ formatPercent(item.zhangdiefu) }}
                                </span>
                            </td>
                            <td>{{ formatVolume(item.volume) }}</td>
                            <td>{{ formatAmount(item.amount) }}</td>
                        </tr>
                    </tbody>
                </table>
                
                <!-- 无数据提示 -->
                <el-empty v-else description="暂无指数数据" :image-size="200">
                    <el-button type="primary" @click="refreshData">刷新数据</el-button>
                </el-empty>
            </div>

            <!-- 详细信息面板 -->
            <div class="zhishu-detail-panel" v-if="selectedDate">
                <div class="panel-header">
                    <h3>{{ formatDate(selectedDate) }} 指数详情</h3>
                    <button class="close-btn" @click="selectedDate = null">×</button>
                </div>
                <div class="detail-content">
                    <el-row :gutter="20">
                        <el-col :span="6">
                            <el-card class="stat-card">
                                <div class="stat-title">指数名称</div>
                                <div class="stat-value">{{ getSelectedData().zsName || '-' }}</div>
                            </el-card>
                        </el-col>
                        <el-col :span="6">
                            <el-card class="stat-card">
                                <div class="stat-title">收盘价</div>
                                <div class="stat-value" :style="{ color: getChangeColor(getSelectedData().zhangdiee) }">
                                    {{ formatNumber(getSelectedData().close) }}
                                </div>
                            </el-card>
                        </el-col>
                        <el-col :span="6">
                            <el-card class="stat-card">
                                <div class="stat-title">涨跌额</div>
                                <div class="stat-value" :style="{ color: getChangeColor(getSelectedData().zhangdiee) }">
                                    {{ formatNumber(getSelectedData().zhangdiee) }}
                                </div>
                            </el-card>
                        </el-col>
                        <el-col :span="6">
                            <el-card class="stat-card">
                                <div class="stat-title">涨跌幅</div>
                                <div class="stat-value" :style="{ color: getChangeColor(getSelectedData().zhangdiefu) }">
                                    {{ formatPercent(getSelectedData().zhangdiefu) }}
                                </div>
                            </el-card>
                        </el-col>
                    </el-row>
                    <el-row :gutter="20" style="margin-top: 20px;">
                        <el-col :span="8">
                            <el-card class="stat-card">
                                <div class="stat-title">成交额</div>
                                <div class="stat-value">{{ formatAmount(getSelectedData().amount) }}</div>
                            </el-card>
                        </el-col>
                        <el-col :span="8">
                            <el-card class="stat-card">
                                <div class="stat-title">成交量</div>
                                <div class="stat-value">{{ formatVolume(getSelectedData().volume) }}</div>
                            </el-card>
                        </el-col>
                        <el-col :span="8">
                            <el-card class="stat-card">
                                <div class="stat-title">开盘价</div>
                                <div class="stat-value">{{ formatNumber(getSelectedData().open) }}</div>
                            </el-card>
                        </el-col>
                    </el-row>
                </div>
            </div>

            <!-- 统计信息 -->
            <div class="statistics-panel" v-if="zhishuData.length > 0">
                <h3>统计信息</h3>
                <el-row :gutter="20">
                    <el-col :span="6">
                        <el-card class="stat-card">
                            <div class="stat-title">数据记录数</div>
                            <div class="stat-value">{{ zhishuData.length }}</div>
                        </el-card>
                    </el-col>
                    <el-col :span="6">
                        <el-card class="stat-card">
                            <div class="stat-title">最新收盘价</div>
                            <div class="stat-value" :style="{ color: getChangeColor(zhishuData[0]?.zhangdiee) }">
                                {{ formatNumber(zhishuData[0]?.close) }}
                            </div>
                        </el-card>
                    </el-col>
                    <el-col :span="6">
                        <el-card class="stat-card">
                            <div class="stat-title">最新涨跌幅</div>
                            <div class="stat-value" :style="{ color: getChangeColor(zhishuData[0]?.zhangdiefu) }">
                                {{ formatPercent(zhishuData[0]?.zhangdiefu) }}
                            </div>
                        </el-card>
                    </el-col>
                    <el-col :span="6">
                        <el-card class="stat-card">
                            <div class="stat-title">最后更新时间</div>
                            <div class="stat-value">{{ lastUpdateTime }}</div>
                        </el-card>
                    </el-col>
                </el-row>
            </div>
        </div>
    `,
    
    data() {
        // 获取当前日期并格式化为YYYY-MM-DD
        const today = new Date();
        const currentDate = today.getFullYear() + '-' + 
                          String(today.getMonth() + 1).padStart(2, '0') + '-' + 
                          String(today.getDate()).padStart(2, '0');
        
        return {
            loading: false,
            lastUpdateTime: new Date().toLocaleString(),
            zhishuData: [],
            selectedDate: null,
            selectedQueryDate: currentDate,
            currentQueryType: 'date' // 'recent', 'date' - 改为date以默认加载当前日期数据
        }
    },
    
    methods: {
        async refreshData() {
            this.loading = true;
            try {
                await this.loadZhishuData();
                this.lastUpdateTime = new Date().toLocaleString();
            } finally {
                this.loading = false;
            }
        },
        
        async loadZhishuData() {
            try {
                let url;
                if (this.currentQueryType === 'date' && this.selectedQueryDate) {
                    // 格式化日期为yyyyMMdd
                    const formattedDate = this.selectedQueryDate.replace(/-/g, '');
                    url = `/api/zhishu/${formattedDate}`;
                    console.log('正在请求指定日期指数数据URL:', url);
                } else {
                    url = `/api/zhishu/get`;
                    console.log('正在请求全部指数数据URL:', url);
                }
                
                const response = await axios.get(url);
                console.log('指数数据API响应:', response.data);
                
                if (response.data && response.data.code === 200) {
                    const zhishuData = response.data.data || [];
                    this.processZhishuData(zhishuData);
                    console.log('成功加载指数数据');
                } else if (Array.isArray(response.data)) {
                    // 直接返回数组的情况
                    this.processZhishuData(response.data);
                    console.log('成功加载指数数据');
                } else {
                    console.error('指数数据格式异常:', response.data);
                }
            } catch (error) {
                console.error('加载指数数据失败:', error);
                if (window.ElMessage) {
                    window.ElMessage.error('数据加载失败: ' + (error.response?.data?.message || error.message));
                }
            }
        },
        
        async queryByDate() {
            if (!this.selectedQueryDate) {
                if (window.ElMessage) {
                    window.ElMessage.warning('请选择查询日期');
                }
                return;
            }
            
            this.currentQueryType = 'date';
            this.selectedDate = null; // 清除之前的选择
            await this.refreshData();
        },
        
        async loadRecentData() {
            this.currentQueryType = 'recent';
            this.selectedQueryDate = null;
            this.selectedDate = null; // 清除之前的选择
            await this.refreshData();
        },
        
        handleDateChange(value) {
            // 日期改变时自动查询
            if (value) {
                this.queryByDate();
            }
        },

        processZhishuData(data) {
            console.log('开始处理指数数据:', data);
            
            if (!Array.isArray(data)) {
                console.error('指数数据格式错误: 不是数组格式');
                this.zhishuData = [];
                return;
            }

            // 按日期排序
            let sortedData = data.sort((a, b) => new Date(b.dateTime) - new Date(a.dateTime));
            
            // 如果是查询最近数据，只取前5条
            if (this.currentQueryType === 'recent') {
                sortedData = sortedData.slice(0, 5);
            }
            
            this.zhishuData = sortedData;
            console.log('处理后的指数数据:', this.zhishuData);
        },
        
        resetSelection() {
            this.selectedDate = null;
        },
        
        getRowClass(item) {
            return {
                'selected-row': this.selectedDate === item.dateTime
            };
        },
        
        handleRowClick(item) {
            if (this.selectedDate === item.dateTime) {
                this.selectedDate = null;
            } else {
                this.selectedDate = item.dateTime;
            }
        },
        
        formatDate(dateStr) {
            if (!dateStr) return '';
            if (dateStr.length === 8) {
                return `${dateStr.substring(0, 4)}-${dateStr.substring(4, 6)}-${dateStr.substring(6, 8)}`;
            }
            return dateStr;
        },
        
        formatNumber(value) {
            if (!value && value !== 0) return '-';
            const num = parseFloat(value);
            return num.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
        },
        
        formatPercent(value) {
            if (!value && value !== 0) return '-';
            const num = parseFloat(value);
            return `${num.toFixed(2)}%`;
        },
        
        formatVolume(value) {
            if (!value || value === '0' || value === '0.00') return '--';
            const num = parseFloat(value);
            if (num >= 100000000) {
                return (num / 100000000).toFixed(2) + '亿';
            } else if (num >= 10000) {
                return (num / 10000).toFixed(2) + '万';
            }
            return num.toFixed(0);
        },
        
        formatAmount(value) {
            if (!value || value === '0' || value === '0.00') return '--';
            const num = parseFloat(value);
            if (num >= 100000000) {
                return (num / 100000000).toFixed(2) + '亿';
            } else if (num >= 10000) {
                return (num / 10000).toFixed(2) + '万';
            }
            return num.toFixed(2);
        },
        
        getChangeColor(value) {
            if (!value && value !== 0) return '#606266';
            const num = parseFloat(value);
            if (num > 0) return '#f56c6c'; // 红色涨
            if (num < 0) return '#67c23a'; // 绿色跌
            return '#606266'; // 灰色平
        },
        
        getSelectedData() {
            return this.zhishuData.find(item => item.dateTime === this.selectedDate) || {};
        }
    },
    
    mounted() {
        console.log('指数数据组件启动');
        // 默认加载当前日期的数据
        this.refreshData();
    }
};